package andrei.mower2.main;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import andrei.mower2.business.MowerDriver;
import andrei.mower2.business.output.ConsoleOutputter;
import andrei.mower2.business.output.FileOutputter;
import andrei.mower2.io.MowerInputReader;
import andrei.mower2.io.file.MowerFileInputReader;
import andrei.mower2.main.i18n.MessageUtils;

public class Main {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

	@Option(name="-f", aliases={"--file"}, required=true)
	private String file;
	
	public static void main(String[] args) {
		Main main = new Main();
		main.processArgs(args);
		main.start();		
	}
	
	private void processArgs(String[] args) {
		CmdLineParser parser = new CmdLineParser(this);
		
		try {
            parser.parseArgument(args);
        } catch(CmdLineException e) {
        	System.err.println(MessageUtils.getMessage("error.main.file"));
            System.err.println(MessageUtils.getMessage("error.main.exampleLabel"));
            System.err.println("\t" + MessageUtils.getMessage("error.main.example"));
            System.exit(1);
        }
	}
	
	private void start() {
		LOGGER.info(MessageUtils.getMessage("info.main.fileProcessStart", file));
		checkFile();
		try (MowerInputReader mowerInputReader = 
				new MowerFileInputReader(Files.newBufferedReader(Paths.get(file), StandardCharsets.ISO_8859_1))) {
			 
			new MowerDriver(mowerInputReader, 
					new ConsoleOutputter(), 
					new FileOutputter(file)).driveMowers();			 
			
		} catch(Exception e) {
			LOGGER.error(e.getMessage());
			System.exit(1);
		}
		LOGGER.info(MessageUtils.getMessage("info.main.fileProcessEnd", file));
	}
	
	private void checkFile() {
		File f = new File(file);
		if(!f.exists()) {
			LOGGER.error(MessageUtils.getMessage("error.main.fileNotFound", file));
			System.exit(1);
		}
	}
}
